package org.sample.recursion;

import java.io.File;
import java.util.Stack;

public class DeleteFile {

    private static int count = 0;

    public static void main(String[] args) {
        deleteAll_(new File("D:/新建文件夹/新建文件夹 - 副本"));
        System.out.println(count);
    }

    public static void deleteAll_(File root) {
        Stack<File> stack = new Stack<File>();
        File current = root;
        while (!stack.empty() || current != null) {
            count++;
            if (isDelete(current)) {
                current.delete();
                current = null;
            } else {
                stack.push(current);
                for (File file : current.listFiles()) {
                    if (isDelete(file)) {
                        file.delete();
                    } else {
                        stack.push(file);
                    }
                }
            }
            if (!stack.empty())
                current = stack.pop();
        }
    }

    public static void deleteAll(File file) {
        count++;
        if (isDelete(file)) {
            file.delete();
        } else {
            for (File tmp : file.listFiles()) {
                deleteAll(tmp);
                file.delete();
            }
        }
    }

    public static boolean isDelete(File file) {
        return (file.isFile() || file.list().length == 0);
    }
}